import elUtil from "../utils/elUtil.js";
import {elEventEmitter} from "../utils/elEventEmitter.js";
import {eventEmitter} from "../model/EventEmitter.js";

/**
 * 判断url是否是产品管理页面
 * @param url {string}
 */
const isGoodsSalePage = (url = window.location.href) => {
    return url.endsWith('ksjhaoka.com/#/goods/sale');
}


const userID = 'mNgPsRk2118639'


/**
 * 获取推广中心数据(当前页)
 */
const getPromotionCenterData = async () => {
    const elList = await elUtil.findElements('.app-main .el-row>div')
    const list = [];
    for (const el of elList) {
        const data = {};
        data["运营商"] = el.querySelector(".goods-header-title").textContent.match(/运营商：(.+)/)[1];
        data["上架时间"] = el.querySelector(".goods-header-time").textContent.match(/上架时间：(.+)/)[1];
        //原始标题
        const originalTitle = el.querySelector(".overflow-ellipsis").textContent;
        data["卡名"] = originalTitle.substring(2, originalTitle.indexOf("卡") + 1);
        data["原始标题"] = originalTitle;
        const tempTitleInfo = originalTitle.substring(originalTitle.indexOf("卡") + 1);
        const monthlyRentIndexOf = tempTitleInfo.indexOf("元");
        let temp_monthlyRent;
        let mainParameter;//主要参数
        if (monthlyRentIndexOf !== -1) {
            temp_monthlyRent = tempTitleInfo.substring(0, monthlyRentIndexOf);
            mainParameter = tempTitleInfo.substring(monthlyRentIndexOf + 1, tempTitleInfo.length)
        } else {
            temp_monthlyRent = "未描述";
            mainParameter = "获取失败";
        }
        data["主要参数"] = mainParameter;
        data["月租"] = temp_monthlyRent;
        const tagsEl = el.querySelectorAll(".goods-tab>span");
        const placeOfBelonging = tagsEl[0].textContent;
        data["归属地"] = placeOfBelonging.includes("归属地") ? placeOfBelonging.match(/(.+)归属地/)[1] : placeOfBelonging;
        data["是否支持选号"] = mainParameter.includes("支持选号") ? "是" : "未知";
        data["是否永久套餐"] = mainParameter.includes("永久套餐") ? "是" : "未知";
        data["是否支持结转"] = mainParameter.includes("支持结转") ? "是" : "未知";
        data["是否长期套餐"] = mainParameter.includes("长期套餐") ? "是" : "未知";
        data["快递"] = tagsEl[1].textContent;
        data["合约"] = tagsEl[2].textContent;
        data["年龄要求"] = tagsEl[3].textContent;
        let tempActivationPlan;
        if (tagsEl.length === 5) {
            tempActivationPlan = tagsEl[4].textContent;
        } else {
            tempActivationPlan = "未描述"
        }
        data["激活方案"] = tempActivationPlan;
        data["佣金"] = el.querySelector(".goods-brokerage div").textContent;
        for (const li of el.querySelectorAll(".goods-info-ul>.goods-info-li")) {
            const strings = li.querySelector(".goods-info-value").textContent.split("：");
            data[strings[0]] = strings[1];
        }
        data["img"] = el.querySelector(".goods-img").src;
        for (const key in data) {
            data[key] = data[key].trim();
        }
        data['下单地址'] = `https://ym.ksjhaoka.com/show?s=${userID}&id=` + data['产品ID']
        list.push(data);
    }
    return list;
}

/**
 * 追加产品中心的推广中心数据
 * 追加的数据会在原列表展示
 * @returns {Promise<boolean>} 是否追加了数据
 */
const appendPromotionCenterData = async (list) => {
    const pageList = await getPromotionCenterData()
    const newDataList = []
    const oldSize = list.length;
    for (let newData of pageList) {
        if (list.some(item => item["产品ID"] === newData["产品ID"])) {
            continue
        }
        newDataList.push(newData)
    }
    for (let data of newDataList) {
        list.push(data)
    }
    // 返回是否追加了数据
    return oldSize < list.length
}


/**
 * 获取未上架或已下架的数据列表
 * 未上架和已下架的产品，没法通过产品ID访问商品详情页
 * @returns {Promise<*[]>}
 */
const getNotAvailableDataList = async () => {
    const elList = await elUtil.findElements('.el-row .goods-list')
    const list = [];
    for (const el of elList) {
        const data = {};
        let operator = el.querySelector('.goods-header-title').textContent.trim();
        operator = operator.split('：');
        // 运营商
        data[operator[0]] = operator[1]
        let listingTime = el.querySelector('.goods-header-time').textContent.trim()
        listingTime = listingTime.split('：');
        // 上架时间
        data[listingTime[0]] = listingTime[1]
        // 图片
        data['img'] = el.querySelector('img.goods-img').src;
        const tag = []
        data['title'] = el.querySelector('h3.overflow-ellipsis').textContent
        for (let tagEl of el.querySelectorAll('.goods-box>.goods-tab>span')) {
            tag.push(tagEl.textContent)
        }
        data['tag'] = tag
        try {
            data['佣金'] = el.querySelector('.goods-brokerage>div').textContent.trim()
        } catch (e) {
            data['佣金'] = '未描述'
        }
        const goodsInfoEls = el.querySelectorAll('.goods-info-li>div.goods-info-value');
        for (let goodsInfoEl of goodsInfoEls) {
            const arr = goodsInfoEl.textContent.split('：');
            data[arr[0]] = arr[1]
        }
        list.push(data)
    }
    return list
}


/**
 * 安装顶部三个标签监听器(未上架、推广中心、已下架)
 */
const installTopTabsListener = () => {

    //前一个标签
    let agoLabel;
    elUtil.findElement('.app-container .type-box').then(el => {
        elEventEmitter.addEvent(el, 'click', (event) => {
            /**
             *
             * @type {Element|Document}
             */
            const targetEl = event.target;
            const label = targetEl.textContent.trim()
            if (targetEl.className !== 'type-activate') {
                return
            }
            if (agoLabel === label) {
                //前一个点击的标签和当前点击的标签相同，则不执行任何操作，避免重复执行
                return;
            }
            //更新上一个标签
            agoLabel = label
            eventEmitter.send('产品管理子标签切换', label)
        })
    })
}


//产品管理
export default {
    isGoodsSalePage,
    appendPromotionCenterData,
    getPromotionCenterData,
    getNotAvailableDataList,
    installTopTabsListener
}
